package com.boot2.core.utils;

import okhttp3.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.net.ssl.*;
import java.io.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * http工具类，底层为okhttp,用来取代apache的httpClient
 * 
 * @description:
 * @CreateDate:2018年3月29日 下午2:55:26
 * @Author:zhangweilin
 */
@SuppressWarnings("all")
public class HttpsClient_OK_Bak {
	protected static Log log = LogFactory.getLog(HttpsClient_OK_Bak.class);
	private static String token;
	public static String MEDIA_TYPE_JSON = "application/json; charset=utf-8"; // json请求
	public static String MEDIA_TYPE_FORM = "application/x-www-form-urlencoded; charset=utf-8"; // 表单请求
	/** 使用volatile双重校验锁 **/
	private static volatile Semaphore semaphore = null;
	private static volatile OkHttpClient okHttpClient = null;
	private static volatile OkHttpClient okHttpsClient = null;

	/** 建立单例模式 */
	public static Semaphore getSemaphoreInstance() {
		// 只能0个线程同时访问
		synchronized (HttpsClient_OK_Bak.class) {
			if (semaphore == null) {
				semaphore = new Semaphore(0);
			}
		}
		return semaphore;
	}

	/** 建立单例模式 */
	public static OkHttpClient getHttpInstance() {
		synchronized (HttpsClient_OK_Bak.class) {
			if (okHttpClient == null) {
				// 这里是以毫秒为单位，1000 毫秒 = 1秒
				okHttpClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
					@Override
					public Response intercept(Chain chain) throws IOException {
						Request request = chain.request().newBuilder().addHeader("x-access-token", getToken()).build();
						return chain.proceed(request);
					}
				}).connectTimeout(5000, TimeUnit.SECONDS)// 设置超时时间
						.readTimeout(5000, TimeUnit.SECONDS)// 设置读取超时时间
						.writeTimeout(5000, TimeUnit.SECONDS)// 设置写入超时时间
						.build();
			}
		}
		return okHttpClient;
	}

	/** 建立单例模式 */
	public static OkHttpClient getHttpsInstance() {
		synchronized (HttpsClient_OK_Bak.class) {
			if (okHttpsClient == null) {
				// 这里是以毫秒为单位，1000 毫秒 = 1秒
				okHttpsClient = new OkHttpClient().newBuilder().addInterceptor(new Interceptor() {
					@Override
					public Response intercept(Chain chain) throws IOException {
						Request request = chain.request().newBuilder().addHeader("x-access-token", getToken()).build();
						return chain.proceed(request);
					}
				}).sslSocketFactory(createSSLSocketFactory()).hostnameVerifier(new TrustAllHostnameVerifier()).connectTimeout(5000, TimeUnit.SECONDS)// 设置超时时间
						.readTimeout(5000, TimeUnit.SECONDS)// 设置读取超时时间
						.writeTimeout(5000, TimeUnit.SECONDS)// 设置写入超时时间
						.build();
			}
		}

		return okHttpsClient;
	}

	public static void setToken(String token0) {
		token = token0;
	}

	private static String getToken() {
		return token = token == null ? "" : token;
	}

	/**
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	private static Call createCall(String url, Map<String, Object> params) {
		// 补全请求地址,【%s?%s或者%s/%s的使用】第一个%s代表第一个参数，第二个?代表是请求地址的?后面%s代表是组装戳参数,如：
		// http://localhost:8080/api/test.do?userId=1212&deviceInfo=PC
//		String requestUrl = String.format("%s?%s", url, concatParams(params).toString());
		String requestUrl = getFullUrl(url, params);
		// 创建一个请求
		log.info("requestUrl:" + requestUrl);
		Request request = new Request.Builder().url(requestUrl).build();
		return getHttpInstance().newCall(request);
	}

	/**
	 * 
	 * @param url
	 * @param headerMap
	 * @param params
	 * @return
	 */
	private static Call createCall(String url, Map<String, String> headerMap, Map<String, Object> params) {
		// 补全请求地址,【%s?%s或者%s/%s的使用】第一个%s代表第一个参数，第二个?代表是请求地址的?后面%s代表是组装戳参数,如：
		// http://localhost:8080/api/test.do?userId=1212&deviceInfo=PC
		String requestUrl = getFullUrl(url, params);
		// 创建一个请求
		log.info("requestUrl:" + requestUrl);
		Request.Builder builder = new Request.Builder();
		if (null != headerMap) {
			Set<Entry<String, String>> entrySet = headerMap.entrySet();
			for (Entry<String, String> entry : entrySet) {
				builder.addHeader(entry.getKey(), entry.getValue());
			}
		}
		Request request = builder.url(requestUrl).build();
		return getHttpInstance().newCall(request);
	}

	/**
	 * 拼全路径
	 * @param url
	 * @param params
	 * @return
	 */
	public static String getFullUrl(String url, Map<String, Object> params) {
		String requestUrl = url;
		if (null!=params) {
			requestUrl = String.format("%s?%s", url, concatParams(params).toString());
		}
		return requestUrl;
	}

	/**
	 * https请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	private static Call createCalls(String url, Map<String, Object> params) {
		// 补全请求地址,【%s?%s或者%s/%s的使用】第一个%s代表第一个参数，第二个?代表是请求地址的?后面%s代表是组装戳参数,如：
		// http://localhost:8080/api/test.do?userId=1212&deviceInfo=PC
//		String requestUrl = String.format("%s?%s", url, concatParams(params).toString());
		String requestUrl = getFullUrl(url, params);
		// 创建一个请求
		Request request = new Request.Builder().url(requestUrl).build();
		return getHttpsInstance().newCall(request);
	}

	/**
	 * okHttp createCall
	 * 
	 * @param url
	 *            接口地址
	 * @param params
	 *            请求参数
	 */
	private static Call createCalls(String url, Map<String, String> headerMap, Map<String, Object> params) {
		// 补全请求地址,【%s?%s或者%s/%s的使用】第一个%s代表第一个参数，第二个?代表是请求地址的?后面%s代表是组装戳参数,如：
		// http://localhost:8080/api/test.do?userId=1212&deviceInfo=PC
//		String requestUrl = String.format("%s?%s", url, concatParams(params).toString());
		String requestUrl = getFullUrl(url, params);

		// 创建一个请求
		log.info("requestUrl:" + requestUrl);
		Request.Builder builder = new Request.Builder();
		if (null != headerMap) {
			Set<Entry<String, String>> entrySet = headerMap.entrySet();
			for (Entry<String, String> entry : entrySet) {
				builder.addHeader(entry.getKey(), entry.getValue());
			}
		}
		// 创建一个请求
		Request request = builder.url(requestUrl).build();
		return getHttpsInstance().newCall(request);
	}

	/**
	 * 发起get请求
	 * 
	 * @param url
	 * @param params
	 *            参数
	 * @return
	 */
	public static String get(String url, Map<String, Object> params) {
		log.info("请求url: " + url + ",请求参数:" + (params == null ? "" : params.toString()));
		try {
			// 创建请求对象
			Call call = null;
			if (url.startsWith("http://")) {
				call = createCall(url, params);
			} else if (url.startsWith("https://")) {
				call = createCalls(url, params);
			}
			Response response = call.execute();
			if (response != null && null != response.body()) {
				if (response.isSuccessful()) {
					return convertToString(response.body().byteStream());
				} else {
					return convertToString(response.body().byteStream());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起get请求
	 * 
	 * @param url
	 * @param headerMap
	 *            header头
	 * @param params
	 *            请求参数
	 * @return
	 */
	public static String getWithHeader(String url, Map<String, String> headerMap, Map<String, Object> params) {
		log.info("请求url: " + url + ",请求参数:" + (params == null ? "" : params.toString()));
		try {
			// 创建请求对象
			Call call = null;
			if (url.startsWith("http://")) {
				call = createCall(url, headerMap, params);
			} else if (url.startsWith("https://")) {
				call = createCalls(url, headerMap, params);
			}
			Response response = call.execute();
			if (response != null && null != response.body()) {
				if (response.isSuccessful()) {
					return convertToString(response.body().byteStream());
				} else {
					return convertToString(response.body().byteStream());
				}
				// Collection<String> readLines = IOUtil.readLines(byteStream);
				// System.out.println(readLines);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起get请求
	 * 
	 * @param url
	 * @param params
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */
	public static Map<String, Object> getWithReturnHeader(String url, Map<String, Object> params) {
		log.info("请求url: " + url + ",请求参数:" + params.toString());
		// 创建请求对象
		Call call = null;
		if (url.startsWith("http://")) {
			call = createCall(url, params);
		} else if (url.startsWith("https://")) {
			call = createCalls(url, params);
		}
		String result = "";
		try {
			Response response = call.execute();
			Headers headers = response.headers();
			if (response != null && null != response.body()) {
				if (response.isSuccessful()) {
					result = convertToString(response.body().byteStream());
				} else {
					result = convertToString(response.body().byteStream());
				}
				// Collection<String> readLines = IOUtil.readLines(byteStream);
				// System.out.println(readLines);
			}

			Map<String, Object> resultMap = new HashMap<String, Object>(2);
			resultMap.put("result", result);
			resultMap.put("headers", headers);
			return resultMap;

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 发起get请求
	 * 
	 * @param url
	 * @param headerMap
	 *            请求的header
	 * @param params
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */
	public static Map<String, Object> getWithHeaderAndReturnHeader(String url, Map<String, String> headerMap, Map<String, Object> params) {
		log.info("请求url: " + url + ",请求参数:" + params.toString());
		// 创建请求对象
		Call call = null;
		if (url.startsWith("http://")) {
			call = createCall(url, headerMap, params);
		} else if (url.startsWith("https://")) {
			call = createCalls(url, headerMap, params);
		}
		String result = "";
		try {
			Response response = call.execute();
			Headers headers = response.headers();
			if (response != null && null != response.body()) {
				if (response.isSuccessful()) {
					result = convertToString(response.body().byteStream());
				} else {
					result = convertToString(response.body().byteStream());
				}
				// Collection<String> readLines = IOUtil.readLines(byteStream);
				// System.out.println(readLines);
			}

			Map<String, Object> resultMap = new HashMap<String, Object>(2);
			resultMap.put("result", result);
			resultMap.put("headers", headers);
			return resultMap;

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * @description convertStreamToString @Author liangjl @Date 2018年2月9日
	 *              下午3:02:00 @param is @return 参数 @return String 返回类型 @throws
	 */
	private static String convertToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder buffer = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				buffer.append(line + "\r");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return buffer.toString();
	}

	/**
	 * @description convertStr @Author liangjl @Date 2018年2月9日 下午3:01:49 @param
	 *              is @return @throws IOException 参数 @return String 返回类型 @throws
	 */
	private static String convertStr(InputStream is) throws IOException {
		OutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString();
	}

	/**
	 * 发起post请求
	 * 
	 * @param url
	 * @param reqMap
	 *            请求参数
	 * @return
	 */
	public static String postForm(String url, Map<String, Object> reqMap) {
		if (url.startsWith("https://")) {
			return posts(url, reqMap, MEDIA_TYPE_FORM);
		}

		try {
			RequestBody body = createRequestBody(MEDIA_TYPE_FORM, reqMap);
			return sendReq(url, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起post请求
	 * 
	 * @param url
	 * @param headerMap
	 *            header参数
	 * @param reqMap
	 *            请求参数
	 * @return
	 */
	public static String postFormWithHeader(String url, Map<String, String> headerMap, Map<String, Object> reqMap) {
		if (url.startsWith("https://")) {
			return posts(url, reqMap, MEDIA_TYPE_FORM);
		}

		try {
			RequestBody body = createRequestBody(MEDIA_TYPE_FORM, reqMap);
			return sendReq(url, headerMap, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起post请求
	 * 
	 * @param url
	 * @param reqMap
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */
	public static Map<String, Object> postFormWithReturnHeader(String url, Map<String, Object> reqMap) {
		if (url.startsWith("https://")) {
			return postsWithReturnHeader(url, reqMap, MEDIA_TYPE_FORM);
		}
		RequestBody body = createRequestBody(MEDIA_TYPE_FORM, reqMap);
		try {
			return sendReqWithReturnHeader(url, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发起post请求
	 * 
	 * @param url
	 * @param headerMap
	 *            请求header参数
	 * @param reqMap
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */
	public static Map<String, Object> postFormWithHeaderAndReturnHeader(String url, Map<String, String> headerMap, Map<String, Object> reqMap) {
		if (url.startsWith("https://")) {
			return postsWithReturnHeader(url, reqMap, MEDIA_TYPE_FORM);
		}
		RequestBody body = createRequestBody(MEDIA_TYPE_FORM, reqMap);
		try {
			return sendReqWithReturnHeader(url, headerMap, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param json
	 *            请求参数
	 * @return
	 */
	public static String postJson(String url, String json) {
		if (url.startsWith("https://")) {
			return postsJson(url, json, MEDIA_TYPE_JSON);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, null);
			return sendReq(url, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param json
	 *            请求参数
	 * @param paramMap
	 *            请求参数
	 * @return
	 */
	public static String postJsonAndParamMap(String url, String json, Map<String, String> paramMap) {
		url = concatParams(url, paramMap);
		if (url.startsWith("https://")) {
			return postsJsonAndHeaderAndParamMapWithHeader(url, json, MEDIA_TYPE_JSON, paramMap, null);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, paramMap);
			return sendReq(url, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param headerMap
	 *            请求header参数
	 * @param json
	 *            请求参数
	 * @return
	 */
	public static String postJsonWithHeader(String url, Map<String, String> headerMap, String json) {
		if (url.startsWith("https://")) {
			return postsJsonAndHeaderAndParamMapWithHeader(url, json, MEDIA_TYPE_JSON, null, headerMap);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, null);
			return sendReq(url, headerMap, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param headerMap
	 *            请求header参数
	 * @param json
	 *            请求参数
	 * @return
	 */
	public static String postJsonAndParamMapWithHeader(String url, Map<String, String> headerMap, String json, Map<String, String> paramMap) {
		url = concatParams(url, paramMap);
		if (url.startsWith("https://")) {
			return postsJsonAndHeaderAndParamMapWithHeader(url, json, MEDIA_TYPE_JSON, paramMap, headerMap);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, paramMap);
			return sendReq(url, headerMap, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param json
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */
	public static Map<String, Object> postJsonWithReturnHeader(String url, String json) {
		if (url.startsWith("https://")) {
			return postsJsonAndHeaderAndParamMapWithReturnHeader(url, json, MEDIA_TYPE_JSON, null, null);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, null);
			return sendReqWithReturnHeader(url, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param json
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */
	public static Map<String, Object> postJsonAndParamMapWithReturnHeader(String url, String json, Map<String, String> paramMap) {
		url = concatParams(url, paramMap);
		if (url.startsWith("https://")) {
			return postsJsonAndHeaderAndParamMapWithReturnHeader(url, json, MEDIA_TYPE_JSON, paramMap, null);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, paramMap);
			return sendReqWithReturnHeader(url, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param headerMap
	 *            请求header参数
	 * @param reqMap
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */

	public static Map<String, Object> postJsonWithHeaderAndReturnHeader(String url, Map<String, String> headerMap, String json) {
		if (url.startsWith("https://")) {
			return postsJsonAndHeaderAndParamMapWithReturnHeader(url, json, MEDIA_TYPE_JSON, null, headerMap);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, null);
			return sendReqWithReturnHeader(url, headerMap, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发起json请求
	 * 
	 * @param url
	 * @param headerMap
	 *            请求header参数
	 * @param reqMap
	 *            请求参数
	 * @return 返回一个map,其中key=result时，value为请求返回文本，key=headers，value为头部集合
	 */

	public static Map<String, Object> postJsonAndParamMapWithHeaderAndReturnHeader(String url, Map<String, String> headerMap, String json,
			Map<String, String> paramMap) {
		url = concatParams(url, paramMap);
		if (url.startsWith("https://")) {
			return postsJsonAndHeaderAndParamMapWithReturnHeader(url, json, MEDIA_TYPE_JSON, paramMap, headerMap);
		}

		try {
			RequestBody body = createJsonRequestBodyWithParamMap(MEDIA_TYPE_JSON, json, paramMap);
			return sendReqWithReturnHeader(url, headerMap, body);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @description 创建支持https请求 @Author liangjl @Date 2018年2月9日 下午3:25:47 @param
	 *              url @param reqMap @param contentType 参数 @return void
	 *              返回类型 @throws
	 */
	private static Map<String, Object> postsJsonAndHeaderAndParamMapWithReturnHeader(String url, String json, String contentType, Map<String, String> pararmMap,
			Map<String, String> headerMap) {
		final StringBuilder buffer = new StringBuilder("");
		/** 忽略SSL协议证书 */
		OkHttpClient build = getHttpsInstance();
		final RequestBody body = createJsonRequestBodyWithParamMap(contentType, json, pararmMap);
		Request.Builder builder = new Request.Builder();
		if (null != headerMap) {
			Set<Entry<String, String>> entrySet = headerMap.entrySet();
			for (Entry<String, String> entry : entrySet) {
				builder.addHeader(entry.getKey(), entry.getValue());
			}
		}
		final Request request = builder.url(url).post(body).build();
		final Call call = build.newCall(request);
		final Headers[] headers = new Headers[1];
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String res = response.body().string();
				buffer.append(res);
				headers[0] = response.headers();
				getSemaphoreInstance().release();// 释放
			}
		});

		try {
			getSemaphoreInstance().acquire();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		Map<String, Object> resultMap = new HashMap<String, Object>(2);
		resultMap.put("result", buffer.toString());
		resultMap.put("headers", headers[0]);

		return resultMap;
	}

	private static String sendReq(String url, RequestBody body) throws IOException {
		log.info("请求url: " + url + ",请求参数:" + body.toString());
		final Request request = new Request.Builder().url(url).post(body).build();

		// 创建请求对象
		final Call call = getHttpInstance().newCall(request);
		Response response = call.execute();
		if (response != null && null != response.body()) {
			if (response.isSuccessful()) {
				return convertStr(response.body().byteStream());
			} else {
				return convertStr(response.body().byteStream());
			}
		}
		return "";
	}

	private static String sendReq(String url, Map<String, String> headerMap, RequestBody body) throws IOException {
		log.info("请求url: " + url + ",请求参数:" + body.toString());
		Request.Builder builder = new Request.Builder();
		if (null != headerMap) {
			Set<Entry<String, String>> entrySet = headerMap.entrySet();
			for (Entry<String, String> entry : entrySet) {
				builder.addHeader(entry.getKey(), entry.getValue());
			}
		}

		final Request request = builder.url(url).post(body).build();

		// 创建请求对象
		final Call call = getHttpInstance().newCall(request);
		Response response = call.execute();
		if (response != null && null != response.body()) {
			if (response.isSuccessful()) {
				return convertStr(response.body().byteStream());
			} else {
				return convertStr(response.body().byteStream());
			}
		}
		return "";
	}

	private static Map<String, Object> sendReqWithReturnHeader(String url, RequestBody body) throws IOException {
		// log.info("@see"+getCurrentClassName()+"#createHttpPost,请求url:
		// "+url+",请求参数:"+body.toString());
		log.info("请求url: " + url + ",请求参数:" + body.toString());
		final Request request = new Request.Builder().url(url).post(body).build();
		// 创建请求对象
		final Call call = getHttpInstance().newCall(request);
		Response response = call.execute();
		Headers headers = response.headers();
		String result = "";
		if (response != null && null != response.body()) {
			if (response.isSuccessful()) {
				result = convertStr(response.body().byteStream());
			} else {
				result = convertStr(response.body().byteStream());
			}
		}
		Map<String, Object> resultMap = new HashMap<String, Object>(2);
		resultMap.put("result", result);
		resultMap.put("headers", headers);
		return resultMap;
	}

	private static Map<String, Object> sendReqWithReturnHeader(String url, Map<String, String> headerMap, RequestBody body) throws IOException {
		// log.info("@see"+getCurrentClassName()+"#createHttpPost,请求url:
		// "+url+",请求参数:"+body.toString());
		log.info("请求url: " + url + ",请求参数:" + body.toString());
		Request.Builder builder = new Request.Builder();
		if (null != headerMap) {
			Set<Entry<String, String>> entrySet = headerMap.entrySet();
			for (Entry<String, String> entry : entrySet) {
				builder.addHeader(entry.getKey(), entry.getValue());
			}
		}
		final Request request = builder.url(url).post(body).build();
		// 创建请求对象
		final Call call = getHttpInstance().newCall(request);
		Response response = call.execute();
		Headers headers = response.headers();
		String result = "";
		if (response != null && null != response.body()) {
			if (response.isSuccessful()) {
				result = convertStr(response.body().byteStream());
			} else {
				result = convertStr(response.body().byteStream());
			}
		}
		Map<String, Object> resultMap = new HashMap<String, Object>(2);
		resultMap.put("result", result);
		resultMap.put("headers", headers);
		return resultMap;
	}

	/**
	 * post并获取其header
	 * 
	 * @param url
	 * @param reqMap
	 * @param header
	 * @return
	 */
	// public static Map<String, Object> postWithReturnHeader(String url,
	// Map<String, Object> reqMap, String contentType) {
	// try {
	// RequestBody body = createRequestBody(contentType, reqMap);
	// //
	//// log.info("@see" + getCurrentClassName() + "#createHttpPost,请求url: " + url +
	// ",请求参数:" + body.toString());
	// final Request request = new Request.Builder().url(url).post(body).build();
	// // 创建请求对象
	// final Call call = getHttpInstance().newCall(request);
	// Response response = call.execute();
	// Map<String, Object> resultMap = new HashMap<String, Object>(2);
	// if (response != null) {
	// String result = convertStr(response.body().byteStream());
	// resultMap.put("result", result);
	// }
	// Headers headers = response.headers();
	// resultMap.put("headers", headers);
	// return resultMap;
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return null;
	// }

	/**
	 * 
	 * @description 组装参数
	 * @Author liangjilong
	 * @Date 2017年7月10日 下午5:48:13
	 * @param contentType
	 *            请求头header属性
	 * @param params
	 *            请求参数
	 * @return 参数
	 * @return RequestBody 返回类型
	 */
	private static RequestBody createRequestBody(String contentType, Map<String, Object> params) {
		MediaType type = MediaType.parse(contentType);
		String paramStrs = concatParams(params).toString();
		System.out.println("paramStrs: " + paramStrs);
		RequestBody requestBody = RequestBody.create(type, paramStrs);
		return requestBody;
	}
	//
	// /**
	// * 创建json请求
	// *
	// * @param contentType
	// * @param json
	// * @return
	// */
	// private static RequestBody createJsonRequestBody(String contentType, String
	// json) {
	// MediaType type = MediaType.parse(contentType);
	// RequestBody requestBody = FormBody.create(type, json);
	// return requestBody;
	// }

	/**
	 * 创建json请求
	 * 
	 * @param contentType
	 * @param json
	 * @return
	 */
	private static RequestBody createJsonRequestBodyWithParamMap(String contentType, String json, Map<String, String> paramMap) {
		MediaType type = MediaType.parse(contentType);
		FormBody.Builder builder = new FormBody.Builder();
		// if (paramMap != null) {
		// Set<Entry<String, String>> entrySet = paramMap.entrySet();
		// for (Entry<String, String> entry : entrySet) {
		// builder.add(entry.getKey(), entry.getValue());
		// }
		// }
		RequestBody requestBody = builder.build().create(type, json);
		return requestBody;
	}

	/**
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	private static String concatParams(String url, Map<String, ? extends Object> params) {
		StringBuilder stringBuilder = concatParams(params);
		url = url + "?" + stringBuilder.toString();
		return url;
	}

	/**
	 * @description 拼接参数
	 * @Author liangjilong
	 * @Date 2017年7月11日 上午9:34:00
	 * @param params
	 * @return 参数
	 * @return StringBuilder 返回类型
	 */
	private static StringBuilder concatParams(Map<String, ? extends Object> params) {
		StringBuilder builder = new StringBuilder("");// 请求参数为空给一个默认值空字符串
		// 判断是空
		if (null != params) {
			int i = 0;
			for (String key : params.keySet()) {
				Object value = params.get(key);
				if (value instanceof Collection) {
					Collection collection = (Collection) value;
					for (Object value1 : collection) {
						builder.append(i != 0 ? "&" : "");
						builder.append(key + "[]=" + value1);
						i++;
					}
				} else {
					builder.append(i != 0 ? "&" : "");
					builder.append(key + "=" + value);
					i++;
				}

			}
		}
		System.out.println("组装参数: " + builder.toString());
		log.info("组装参数: " + builder.toString());
		return builder;
	}

	/**
	 * @description 创建支持https请求 @Author liangjl @Date 2018年2月9日 下午3:25:47 @param
	 *              url @param reqMap @param contentType 参数 @return void
	 *              返回类型 @throws
	 */
	private static String posts(String url, Map<String, Object> reqMap, String contentType) {
		final StringBuilder buffer = new StringBuilder("");
		/** 忽略SSL协议证书 */
		OkHttpClient build = getHttpsInstance();
		final RequestBody body = createRequestBody(contentType, reqMap);
		final Request request = new Request.Builder().url(url).post(body).build();
		final Call call = build.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String res = response.body().string();
				buffer.append(res);
				getSemaphoreInstance().release();// 释放
			}
		});

		try {
			getSemaphoreInstance().acquire();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		return buffer.toString();
	}

	/**
	 * @description 创建支持https请求 @Author liangjl @Date 2018年2月9日 下午3:25:47 @param
	 *              url @param reqMap @param contentType 参数 @return void
	 *              返回类型 @throws
	 */
	private static String postsJson(String url, String json, String contentType) {
		final StringBuilder buffer = new StringBuilder("");
		/** 忽略SSL协议证书 */
		OkHttpClient build = getHttpsInstance();
		final RequestBody body = createJsonRequestBodyWithParamMap(contentType, json, null);
		final Request request = new Request.Builder().url(url).post(body).build();
		final Call call = build.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String res = response.body().string();
				buffer.append(res);
				getSemaphoreInstance().release();// 释放
			}
		});

		try {
			getSemaphoreInstance().acquire();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		return buffer.toString();
	}

	/**
	 * @description 创建支持https请求 @Author liangjl @Date 2018年2月9日 下午3:25:47 @param
	 *              url @param reqMap @param contentType 参数 @return void
	 *              返回类型 @throws
	 */
	private static String postsJsonAndHeaderAndParamMapWithHeader(String url, String json, String contentType, Map<String, String> pararmMap,
			Map<String, String> headerMap) {
		final StringBuilder buffer = new StringBuilder("");
		/** 忽略SSL协议证书 */
		OkHttpClient build = getHttpsInstance();
		final RequestBody body = createJsonRequestBodyWithParamMap(contentType, json, pararmMap);
		Request.Builder builder = new Request.Builder();
		if (null != headerMap) {
			Set<Entry<String, String>> entrySet = headerMap.entrySet();
			for (Entry<String, String> entry : entrySet) {
				builder.addHeader(entry.getKey(), entry.getValue());
			}
		}
		final Request request = builder.url(url).post(body).build();
		final Call call = build.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String res = response.body().string();
				buffer.append(res);
				getSemaphoreInstance().release();// 释放
			}
		});

		try {
			getSemaphoreInstance().acquire();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		return buffer.toString();
	}

	/**
	 * @description 创建支持https请求 @Author liangjl @Date 2018年2月9日 下午3:25:47 @param
	 *              url @param reqMap @param contentType 参数 @return void
	 *              返回类型 @throws
	 */
	private static Map<String, Object> postsWithReturnHeader(String url, Map<String, Object> reqMap, String contentType) {
		final StringBuilder buffer = new StringBuilder("");
		/** 忽略SSL协议证书 */
		OkHttpClient build = getHttpsInstance();
		final RequestBody body = createRequestBody(contentType, reqMap);
		final Request request = new Request.Builder().url(url).post(body).build();
		final Call call = build.newCall(request);
		final Headers[] headers = new Headers[1];
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String res = response.body().string();
				buffer.append(res);
				headers[0] = response.headers();
				getSemaphoreInstance().release();// 释放
			}
		});

		try {
			getSemaphoreInstance().acquire();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}

		Map<String, Object> resultMap = new HashMap<String, Object>(2);
		resultMap.put("result", buffer.toString());
		resultMap.put("headers", headers[0]);

		return resultMap;
	}

	/**
	 * @description TrustAllCerts
	 * @ClassName TrustAllCerts
	 * @Date 2018年2月9日 下午3:15:23
	 * @Author liangjl
	 * @Copyright (c) All Rights Reserved, 2018.
	 */
	private static class TrustAllCerts implements X509TrustManager {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		}
	}

	/**
	 * @description 验证所有主机
	 * @ClassName TrustAllHostnameVerifier
	 * @Date 2018年2月9日 下午3:15:34
	 * @Author liangjl
	 * @Copyright (c) All Rights Reserved, 2018.
	 */
	private static class TrustAllHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	/**
	 * @description createSSLSocketFactory @Author liangjl @Date 2018年2月9日
	 *              下午3:15:47 @return 参数 @return SSLSocketFactory 返回类型 @throws
	 */
	private static SSLSocketFactory createSSLSocketFactory() {
		SSLSocketFactory ssfFactory = null;
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, new TrustManager[] { new TrustAllCerts() }, new SecureRandom());
			ssfFactory = sc.getSocketFactory();
		} catch (Exception e) {
		}
		return ssfFactory;
	}
}
